package net.lulihu.common_util.spring;

import net.lulihu.Assert;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.lang.NonNull;

/**
 * Spring的ApplicationContext的持有者,可以用静态方法的方式获取spring容器中的bean
 */
public class SpringContextHolder implements ApplicationContextAware {

    private static ConfigurableApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = (ConfigurableApplicationContext) applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        assertApplicationContext();
        return applicationContext;
    }

    /**
     * 根据bean名称获取bean实例
     *
     * @param beanName bean名称
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) {
        assertApplicationContext();
        return (T) applicationContext.getBean(beanName);
    }

    /**
     * 根据bean类型获取bean实例
     *
     * @param requiredType bean类型
     */
    public static <T> T getBean(Class<T> requiredType) {
        assertApplicationContext();
        return applicationContext.getBean(requiredType);
    }


    /**
     * 注册bean到spring ioc容器中
     *
     * @param obj bean对象
     */
    public void registerBean(Object obj) {
        assertApplicationContext();
        Assert.notNull(obj);
        registerBean(obj.getClass().getName(), obj);
    }

    /**
     * 注册bean到spring ioc容器中
     *
     * @param beanName bean名称
     * @param obj      bean对象
     */
    public void registerBean(String beanName, Object obj) {
        assertApplicationContext();
        Assert.notNull(beanName);
        Assert.notNull(obj);
        applicationContext.getBeanFactory().registerSingleton(beanName, obj);
    }

    private static void assertApplicationContext() {
        Assert.notNull(SpringContextHolder.applicationContext,
                "上下文为空,请检查是否将本对象注入容器");
    }

}
